﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using TuKu.Common;
namespace TuKu.PPS
{
    public partial class ppsPage : Form
    {
        DataTable dtleft = Maticsoft.DBUtility.DbHelperOleDb.Query("select * from urladlist where cateid=1").Tables[0];
        DataTable dtbottom = Maticsoft.DBUtility.DbHelperOleDb.Query("select * from urladlist where cateid=2").Tables[0];
        DataTable urlsubtable = Maticsoft.DBUtility.DbHelperOleDb.Query("select id,url,title,currentpage,picpage,categoryid from urlsubtable ").Tables[0];

        public ppsPage()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 生成展示页第一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMake_Click(object sender, EventArgs e)
        {

            DateTime stime = DateTime.Now;
            int templateid = int.Parse(cmbtemplate.SelectedValue.ToString());
            int urlcateid = int.Parse(cmburlcate.SelectedValue.ToString());
            string strTemplage = getTemplateByid(templateid);
            StringBuilder sb = new StringBuilder();
            TuKu.Model.urltable model = new TuKu.Model.urltable();
            TuKu.BLL.urltable bll = new TuKu.BLL.urltable();
            string strsql = "select top " + txtcount.Text + " id,url,title,picpage,categoryid,pagenumber from urltable where finish=0 and pagenumber<>-1 and categoryid=" + urlcateid.ToString() + " order by id desc";
            DataTable dt = Maticsoft.DBUtility.DbHelperOleDb.Query(strsql).Tables[0];
            string path = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                path = "d:\\pps\\pics\\" + dr["url"].ToString().Replace("http://tu.pps.tv/pics/", "").Replace("/index.html", "");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //model = bll.GetModel(int.Parse(dr["id"].ToString()));
                sb.Append(strTemplage);
                sb.Replace("$title$", dr["title"].ToString()+"(1)");
                sb.Replace("$GoogleSearch_01$", TuKu.Common.Tag.GoogleSearch_01());
                sb.Replace("$GoogleAd_728x90_01$", TuKu.Common.Tag.GoogleAd_728x90_01());
                sb.Replace("$GoogleAd_728x15_01$", TuKu.Common.Tag.GoogleAd_728x15_01());
                sb.Replace("$GoogleAd_728x15_02$", TuKu.Common.Tag.GoogleAd_728x15_02());
                sb.Replace("$picPage$", dr["picPage"].ToString());
                sb.Replace("$pagePager$", MakepagePager(int.Parse(dr["pagenumber"].ToString()), 1));
                sb.Replace("$pageIndex$", "1");
                sb.Replace("$nextUrl$", "2.html");
                sb.Replace("$Encategory$", TuKu.Common.Tag.encategory[int.Parse(dr["categoryid"].ToString())]);
                sb.Replace("$Cncategory$", TuKu.Common.Tag.cncategory[int.Parse(dr["categoryid"].ToString())]);
                //右侧列表
                sb.Replace("$rightList$", RandomList(dtleft, 6));
                //底部列表
                sb.Replace("$bottomList$", RandomList(dtbottom, 11));

                //http://upload.ppstream.com/baike/tu/et/2008-04/12077401274536481_m_4536483_1540.jpg

                sb.Replace("upload.ppstream.com", "tujuduo.com/upload");//更换域名服务器

                FileManager.WriteFile(path + "\\index.html", sb.ToString(), false);
                sb.Remove(0, sb.Length);
                CreateSubPage(int.Parse(dr["url"].ToString().Replace("http://tu.pps.tv/pics/", "").Replace("/index.html", "")), int.Parse(dr["pagenumber"].ToString()), strTemplage);
            }
            DateTime endtime = DateTime.Now;
            TimeSpan sp = endtime - stime;

            MessageBox.Show("用时" + sp.ToString());

        }


        /// <summary>
        /// 生成顶部上一页，下一页
        /// </summary>
        /// <param name="pagenumber">总页数</param>
        /// <param name="currentNumber">1 为index.html页</param>
        /// <returns></returns>
        private string MakepagePager(int pagenumber, int currentNumber)
        {
            StringBuilder sb = new StringBuilder();
            if (currentNumber == 1)
            {
                sb.Append("<a class='on'>1</a>");
                for (int i = 2; i <= pagenumber; i++)
                {
                    sb.Append("<a href='" + i.ToString() + ".html'>" + i.ToString() + "</a>");
                }
            }
            else
            {
                for (int i = 1; i <= pagenumber; i++)
                {
                    if (currentNumber == i)
                    {
                        sb.Append("<a class='on'>" + i.ToString() + "</a>");
                    }
                    else
                    {
                        if (i == 1)
                        {
                            sb.Append("<a href='index.html'>" + i.ToString() + "</a>");
                        }
                        else
                        {
                            sb.Append("<a href='" + i.ToString() + ".html'>" + i.ToString() + "</a>");
                        }
                    }
                }
            }
            return sb.ToString();
        }

        private void ppsPage_Load(object sender, EventArgs e)
        {
            initurlcategory();
            initTemplateCategory();
        }
        void initTemplateCategory()
        {
            DataTable dt = new BLL.urltemplate().GetList(" 1=1 order by tsort").Tables[0];
            cmbtemplate.DataSource = dt;
            cmbtemplate.DisplayMember = "tname";
            cmbtemplate.ValueMember = "id";
        }
        /// <summary>
        /// 获取栏目分类信息
        /// </summary>
        void initurlcategory()
        {
            DataTable dt = new BLL.urlcate().GetList(" 1=1 ").Tables[0];
            this.cmburlcate.DataSource = dt;
            cmburlcate.DisplayMember = "catename";
            cmburlcate.ValueMember = "id";
        }
        /// <summary>
        /// 获得模板信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string getTemplateByid(int id)
        {
            TuKu.BLL.urltemplate bll = new TuKu.BLL.urltemplate();
            TuKu.Model.urltemplate model = bll.GetModel(id);
            return model.tcontent;
        }
        private void CreateSubPage(int urlid, int pagenumber, string strTemplage)
        {
            StringBuilder sb = new StringBuilder();
            //TuKu.BLL.urlsubtable bll = new TuKu.BLL.urlsubtable();
            //DataTable dt = bll.GetList(" rtrim(url)='"+urlid.ToString()+"'").Tables[0];
            DataRow[] drs = urlsubtable.Select(" url='" + urlid.ToString() + "'");
            string path = string.Empty;
            foreach (DataRow dr in drs)
            {
                path = "d:\\pps\\pics\\" + dr["url"].ToString();
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                sb.Append(strTemplage);
                sb.Replace("$title$", dr["title"].ToString() + "(" + dr["currentpage"].ToString() + ")");
                sb.Replace("$GoogleSearch_01$", TuKu.Common.Tag.GoogleSearch_01());
                sb.Replace("$GoogleAd_728x90_01$", TuKu.Common.Tag.GoogleAd_728x90_01());
                sb.Replace("$GoogleAd_728x15_01$", TuKu.Common.Tag.GoogleAd_728x15_01());
                sb.Replace("$GoogleAd_728x15_02$", TuKu.Common.Tag.GoogleAd_728x15_02());
                sb.Replace("$picPage$", dr["picPage"].ToString());
                sb.Replace("$pagePager$", MakepagePager(pagenumber, int.Parse(dr["currentpage"].ToString())));
                sb.Replace("$pageIndex$", dr["currentpage"].ToString());
                if (int.Parse(dr["currentpage"].ToString()) < pagenumber)
                {
                    sb.Replace("$nextUrl$", (int.Parse(dr["currentpage"].ToString()) + 1).ToString() + ".html");
                }
                else
                {
                    sb.Replace("$nextUrl$", "index.html");
                }
                sb.Replace("$Encategory$", TuKu.Common.Tag.encategory[int.Parse(dr["categoryid"].ToString())]);
                sb.Replace("$Cncategory$", TuKu.Common.Tag.cncategory[int.Parse(dr["categoryid"].ToString())]);
                //右侧列表
                sb.Replace("$rightList$", RandomList(dtleft, 6));
                //底部列表
                sb.Replace("$bottomList$", RandomList(dtbottom, 7));

                sb.Replace("upload.ppstream.com", "tujuduo.com/upload");//更换域名服务器

                FileManager.WriteFile(path + "\\" + dr["currentpage"].ToString() + ".html", sb.ToString(), false);
                sb.Remove(0, sb.Length);
            }
        }

        private string RandomList(DataTable dt, int n)
        {
            if (!dt.Columns.Contains("RowID"))
            {
                dt.Columns.Add("RowID", typeof(string));
            }
            foreach (DataRow row in dt.Rows)
            {
                row["RowID"] = Guid.NewGuid().ToString();
            }
            DataView view = new DataView(dt);
            view.Sort = "RowID ASC";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i <= n; i++)
            {
                sb.Append("<li>\r\n");
                sb.Append("<a href=\"" + view[i]["url"] + "\" title=\"" + view[i]["alt"] + "\" target=\"_blank\">\r\n");
                sb.Append("<img src=\"" + view[i]["img"] + "\" alt=\"" + view[i]["alt"] + "\" />\r\n");
                sb.Append("</a>\r\n");
                sb.Append("<span><a href=\"" + view[i]["url"] + "\" title=\"" + view[i]["alt"] + "\" target=\"_blank\">" + view[i]["alt"] + "</a></span>\r\n");
                sb.Append("</li>\r\n");

            }
            return sb.ToString();
        }
        /// <summary>
        /// 生成展示分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMakeOther_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
        }

        private void cmburlcate_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strsql = "select count(id) from urltable where categoryid=" + cmburlcate.SelectedIndex.ToString();
            int count = int.Parse(Maticsoft.DBUtility.DbHelperOleDb.GetSingle(strsql).ToString());
            label1.Text = "记录数：" + count + "预计生成页数" + count * 7 ;
        }
        //-----------------------------------------------列表页处理部份----------------------------------------------------------
        /// <summary>
        /// 生成分类页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            int templateid = int.Parse(cmbtemplate.SelectedValue.ToString());
            int urlcateid = int.Parse(cmburlcate.SelectedValue.ToString());
            string templatecode = getTemplateByid(templateid);

            StringBuilder sb = new StringBuilder();
            StringBuilder tp = new StringBuilder();
            string strsql = "SELECT   id, url, alt, img, orderid, cateid, addtime from urllist where (cateid=" + urlcateid.ToString() + ") order by id desc";
            DataTable dt = Maticsoft.DBUtility.DbHelperOleDb.Query(strsql).Tables[0];
            string path = "d:\\pps\\" + Common.Tag.encategory[urlcateid];
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            int pagecount = dt.Rows.Count / 24;

            int i = 0;
            int j = 1;
            foreach (DataRow dr in dt.Rows)
            {
                i++;
                sb.Append("<li>");
                sb.Append("<a href=\"" + dr["url"].ToString() + "\" title=\"" + dr["alt"].ToString() + "\">");
                sb.Append("<img src=\"" + dr["img"].ToString() + "\" alt=\"" + dr["alt"].ToString() + "\" />");
                sb.Append("</a>");
                sb.Append("<span>");
                sb.Append("<a href=\"" + dr["url"].ToString() + "\" title=\"" + dr["alt"].ToString() + "\">");
                sb.Append(dr["alt"].ToString());
                sb.Append("</a>");
                sb.Append("</span>");
                sb.Append("</li>\r\n");
  
                if (i % 24 == 0)
                {
                    tp.Append(templatecode);
                    tp.Replace("$title$", Common.Tag.cncategory[urlcateid]);
                    tp.Replace("$GoogleSearch_01$",TuKu.Common.Tag.GoogleSearch_01());
                    tp.Replace("$picPage$", sb.ToString());
                    tp.Replace("$pagePager$", MakepagePager(j,pagecount.ToString()));
                    tp.Replace("$encategory$", TuKu.Common.Tag.encategory[int.Parse(dr["cateid"].ToString())]);
                    tp.Replace("$cncategory$", TuKu.Common.Tag.cncategory[int.Parse(dr["cateid"].ToString())]);
                    //底部列表
                    tp.Replace("$rightList$", RandomList(dtleft, 5));
                    tp.Replace("upload.ppstream.com", "tujuduo.com/upload");//更换域名服务器
                    tp.Replace("tu.pps.tv", "tujuduo.com");
                    if (j == 1)
                    {
                        FileManager.WriteFile(path + "\\index.html", tp.ToString(), false);
                    }
                    else
                    {
                        FileManager.WriteFile(path + "\\" + j.ToString() + ".html", tp.ToString(), false);
                    }
                    j++;
                    tp.Remove(0, tp.Length);
                    sb.Remove(0, sb.Length);
                }
            }
            MessageBox.Show("ok");

        }

        private string MakepagePager(int j,string pagecount)
        {
            StringBuilder sb = new StringBuilder();
            if (j < 4)
            {

                for (int i = 1; i <= 7; i++)
                {
                    if (i == j)
                    {
                        sb.Append("<a class='on'>第" + i.ToString() + "页</a>");
                    }
                    else
                    {
                        sb.Append("<a href='" + i.ToString() + ".html'>第" + i.ToString() + "页</a>");
                    }
                }

            }
            else if (j >= 4 && j < int.Parse(pagecount) - 3)
            {
                sb.Append("<a href='index.html'>|&lt;&lt;</a>");
                for (int i = j - 3; i <= j + 3; i++)
                {
                    if (i == j)
                    {
                        sb.Append("<a class='on'>第" + i.ToString() + "页</a>");
                    }
                    else
                    {
                        sb.Append("<a href='" + i.ToString() + ".html'>第" + i.ToString() + "页</a>");
                    }
                }
                sb.Append("<a href='" + pagecount+ ".html'>&gt;&gt;|</a>");
            }
            else
            {
                sb.Append("<a href='index.html'>|&lt;&lt;</a>");
                for (int i = int.Parse(pagecount) - 7; i < int.Parse(pagecount); i++)
                {

                    if (i == j)
                    {
                        sb.Append("<a class='on'>第" + i.ToString() + "页</a>");
                    }
                    else
                    {
                        sb.Append("<a href='" + i.ToString() + ".html'>第" + i.ToString() + "页</a>");
                    }

                }
                sb.Append("<a href='" + pagecount + ".html'>&gt;&gt;|</a>");
            }
            sb.Replace("href='1.html'","href='index.html'");
            return sb.ToString();
        }

    }
}
